#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
//#include <sys/types.h>          /* See NOTES */
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>


int main()
{
	int sockfd;
	struct sockaddr_in addr;
	int result,len;

	char buff[512];

	/* create socket */
	sockfd = socket(AF_INET,SOCK_DGRAM,0);
	if(sockfd == -1) {
		perror("socket");
		exit(1);
	}


	/*init struct sockaddr_in ,and bind sockfd*/
	addr.sin_addr.s_addr = htonl(INADDR_ANY);
	addr.sin_family = AF_INET;
	addr.sin_port = htons(2255);
	len = sizeof(addr);

//	strcpy(buff,"159357");

	struct timeval tv;
	int ret;
	tv.tv_sec = 5;
	tv.tv_usec = 0;
	if (setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)) < 0) {
		/*
		 * setsockopt 函数原型：int setsockopt(int sockfd, int level, int optname, const void *optval, socklen_t optlen);
		 * level specified as SOL_SOCKET
		 *
		 * */
		perror("setsockopt");
	}

	while (1) {

		printf("input some text:\t");
		fgets(buff,512,stdin);

		result = sendto(sockfd, buff, sizeof(buff), 0,(struct sockaddr*)&addr, len);
		if (result == -1) {
			perror("sendto");
			exit(1);
		}
		if (strncmp(buff,"end",3) == 0) {
			break;
		}

		result = recvfrom(sockfd, buff, sizeof(buff), 0, (struct sockaddr*)&addr, &len);//现在遇到的问题就是，这个套接字的地址怎么填写，
		if (result == -1) {
			perror("recvfrom");
			if(ret == EWOULDBLOCK || ret== EAGAIN )
				printf("recvfrom timeout\n");
			else
				printf("recvfrom err:%d\n",ret);
		}
		buff[result] = '\0';

		printf("%s\n",buff);
	}



	exit(0);



}
